async function api_get(url) {
  let response = await fetch(url, {
    method: 'GET',
  });
  return response.text();
}

async function api_post(url, data) {
  let response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': getCookie('csrf_access_token'),
    },
    body: JSON.stringify(data),
  });
  if (response.status === 401) {
    //   <button type="button" class="layui-btn layui-bclassNameimary" lay-on="test-msg-light">浅色提示框</button>
    // 没有权限，拦截进行登录
    location.href = `/login?next=${location.pathname}`;
  } else {
    return await response.json();
  }
}

//fetch 同步请求，已废弃
function request_post(url, data) {
  return fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': getCookie('csrf_access_token'),
    },
    body: JSON.stringify(data),
  }).then(function(response) {
    return response.json();
  }).then(function(ret) {
    return ret;
  })
}


async function api_put(url, data) {
  let response = await fetch(url, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': getCookie('csrf_access_token'),
    },
    body: JSON.stringify(data),
  });
  if (response.status === 401) {
    // 没有权限，拦截进行登录
    location.href = `/login?next=${location.pathname}`;
  } else {
    return await response.json();
  }
}

async function api_delete(url) {
  let response = await fetch(url, {
    method: 'DELETE',
  });
  if (response.status === 401) {
    // 没有权限，拦截进行登录
    location.href = `/login?next=${location.pathname}`;
  } else {
    return await response.json();
  }
}


